package com.xiamo.utils.ws;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xiamo.entity.Message;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author hqf
 * @Date Created in 2022/8/17 17:26
 * @Description
 */
@ServerEndpoint("/ws")
@Component
public class SimpleWebsocketServer {

    /**
     * 存放所有在线的客户端
     */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session) {
        System.out.println(String.format("有新的客户端连接了: %s",session.getId()));
        //将新用户存入在线的组
        clients.put(session.getId(), session);
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println(String.format("有用户断开了, id为: %s",session.getId()));
        //将掉线的用户移除在线的组里
        clients.remove(session.getId());
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
        throwable.printStackTrace();
    }

    /**
     * 收到客户端发来消息
     * @param message 消息对象
     */
    @OnMessage
    public void onMessage(String message) {
        System.out.println(String.format("服务端收到客户端发来的消息: %s",message));
        this.sendAll(message);
    }

    /**
     * 群发消息
     * @param message 消息内容
     */
    private void sendAll(String message) {
        for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
            sessionEntry.getValue().getAsyncRemote().sendText(message);
        }
    }

    public void sendMessagesToAll(List<Message> messages) {
        String messagesJson = JSON.toJSONString(messages);
        this.sendAll(messagesJson);
    }


}
